<?php
/**
 * Created by PhpStorm.
 * User: xuzhong
 * Date: 2025/4/2
 * Time: 13:49
 */
namespace app\admin\service;

use app\admin\common\ServiceResponse;
use app\admin\model\Images;
use app\admin\model\MinerPool as MinerPoolModel;
use function Carbon\interval;
use think\facade\Db;

class MinerPool extends BaseService
{
    use ServiceResponse;

    protected $model;

    public function __construct()
    {
        $this->model = new MinerPoolModel();
        parent::__construct();
    }

    /**
     * @describe 获取销售人员列表
     * @author: 徐众
     * @date: 2025-04-02 13:02:26
     * @param [] type
     * @return Renderable
     */
    public function getList($where, $page, $limit): array
    {
        if (0 >= $page || 100 < $limit) {
            return $this->error(100002);
        }

        $total = $this->model->where($where)->count();
        if (!$total) {
            return $this->success(['list' => [], 'total' => 0]);
        }
        $list = $this->model->where($where)
            ->page($page, $limit)
            ->order('create_time desc')
            ->select()->toArray();
        $avatorId = array_unique(array_column($list,'image'));
        #获取图片url
        $oImages = new Images();
        $avatorUrls = $oImages->getImagesByIds($avatorId);
        $avatorUrls = array_column($avatorUrls, null, 'id');
         foreach ($list as $k=>$v) {
             $list[$k]['currency_name'] = '';
             $list[$k]['image'] = $avatorUrls[$v['image']]['url']??'';
             $list[$k]['imageName'] = $avatorUrls[$v['image']]['name']??'';
             $list[$k]['imageId'] = $avatorUrls[$v['image']]['id']??'';

             $currency_info = Db::name('miner_pool_support_currency')->where('miner_pool_id',$v['id'])->where('is_del',0)->column('currency_id,rating');
             $list[$k]['support_currency'] = '';
             $list[$k]['rating'] = [];
             if($currency_info){
                 $rating = [];
                 $currency_id = array_column($currency_info,'currency_id');
                 $currency = Db::name('product_currency')->whereIn('id',$currency_id)->column('name_short');
                 $list[$k]['currency_name'] = implode(',',$currency);
                 $list[$k]['support_currency'] = implode(',',$currency_id);
                 foreach ($currency_info as $item){

                     if($item['rating']){
                         $rating[$item['currency_id']] = json_decode($item['rating']);
                     }

                 }
                 $list[$k]['rating'] = $rating ;
             }
         }
        return $this->success(['list' => $list, 'total' => $total]);
    }
    /**
     * 创建销售人员
     * @param array $data 创建物流公司的数据
     */
    public function create($data)
    {
        if (empty($data)) {
            return $this->error(500001, '服务器内部错误');
        }

        // 开始事务控制
        Db::startTrans();
        try {
            // 解构并预处理数据
            $currency = $data['support_currency'] ?? '';
            $rating = $data['rating'] ?? [];
            unset($data['support_currency'], $data['rating']);

            // 创建主矿池记录
            $res = $this->model->create($data);
            if (!$res) {
                throw new \Exception('矿池主记录创建失败');
            }

            // 处理关联货币数据
            $currencyIds = explode(',', $currency);
            $supportData = [];
            foreach ($currencyIds as $currencyId) {
                $supportData[] = [
                    'miner_pool_id' => $res->id,
                    'currency_id'   => $currencyId,
                    'rating'        => isset($rating[$currencyId]) ? json_encode($rating[$currencyId]) : null,
                    'creator'       => $data['creator'],
                ];
            }

            // 批量插入关联记录
            if (!empty($supportData)) {
                $supportRes = Db::name('miner_pool_support_currency')->insertAll($supportData);
                if (!$supportRes) {
                    throw new \Exception('关联货币记录插入失败');
                }
            }

            // 提交事务（所有操作成功）
            Db::commit();

            // 记录日志（在事务外执行，避免影响数据一致性）
            $this->logger->logOperation($res->id, 'Minerpool', '创建', '创建矿池');
            return $this->success();

        } catch (\Throwable $th) {
            // 回滚所有数据库操作
            Db::rollback();
            return $this->error(500001, '操作失败：' . $th->getMessage());
        }
    }
    /**
     * 获取销售人员详情
     * @param int $id 物流公司ID
     */
    public function getOneById($id)
    {
        $customerContact = $this->model->find($id);
        if ($customerContact) {
            $data = $customerContact->append(['creator_value']);
        }
        $data = $data->toArray();
        return $this->success($data);
    }
    /**
     * 更新销售人员
     * @param int $id 物流公司ID
     * @param array $data 更新物流公司的数据
     */
    public function update($data)
    {
        // 验证数据完整性
        if (empty($data['id'])) {
            return $this->error(500001, 'ID不能为空');
        }

        $res = $this->model->where('id', $data['id'])->find();
        if (!$res) {
            return false;
        }

        // 提取并验证支持币种和费率数据
        $currency = isset($data['support_currency']) ? explode(',', $data['support_currency']) : [];
        $rating = isset($data['rating']) && is_array($data['rating']) ? $data['rating'] : [];

        // 从主数据中移除这两个字段
        unset($data['support_currency']);
        unset($data['rating']);

        // 开始数据库事务
        Db::startTrans();
        try {
            // 更新矿池基本信息
            $hasChange = false;
            foreach ($data as $key => $value) {
                if ($res->$key != $value) {
                    $res->$key = $value;
                    $hasChange = true;
                }
            }

            if ($hasChange) {
                $res->save();
            }

            // 处理币种支持信息
            $ids = Db::name('miner_pool_support_currency')
                ->where('miner_pool_id', $data['id'])
                ->column('currency_id');

            // 标记要删除的币种 (已不再支持)
            $toDelete = array_diff($ids, $currency);
            if (!empty($toDelete)) {
                Db::name('miner_pool_support_currency')
                    ->where('miner_pool_id', $data['id'])
                    ->whereIn('currency_id', $toDelete)
                    ->update(['is_del' => time()]);
            }

            // 需要新增的币种 (新支持)
            $toAdd = array_diff($currency, $ids);
            if (!empty($toAdd)) {
                $insertData = [];
                foreach ($toAdd as $currencyId) {
                    $rateData = isset($rating[$currencyId]) && is_array($rating[$currencyId])
                        ? $rating[$currencyId]
                        : [];

                    $insertData[] = [
                        'miner_pool_id' => $res->id,
                        'currency_id'   => $currencyId,
                        'rating'        => !empty($rateData) ? json_encode($rateData) : null,
                        'creator'       => $data['creator'] ?? '',
                        'create_time'   => date('Y-m-d H:i:s')
                    ];
                }
                Db::name('miner_pool_support_currency')->insertAll($insertData);
            }

            // 需要更新的币种 (继续支持但有更新)
            $toUpdate = array_intersect($currency, $ids);
            if (!empty($toUpdate)) {
                foreach ($toUpdate as $currencyId) {
                    $rateData = isset($rating[$currencyId]) && is_array($rating[$currencyId])
                        ? $rating[$currencyId]
                        : [];

                    Db::name('miner_pool_support_currency')
                        ->where('miner_pool_id', $res->id)
                        ->where('currency_id', $currencyId)
                        ->update([
                            'rating'      => !empty($rateData) ? json_encode($rateData) : null,
                            'update_time' => date('Y-m-d H:i:s'),
                            'updater'     => $data['creator'] ?? '',
                            'is_del'     => 0 // 确保之前被软删除的恢复状态
                        ]);
                }
            }

            // 提交事务
            Db::commit();

            $this->logger->logOperation($res->id, 'Minerpool', '更新', '更新矿池');
            return $this->success();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $this->error(500001, '更新失败：'.$e->getMessage());
        }
    }

    /**
     * @describe 删除销售人员
     * @author: 徐众
     * @date: 2025-04-02 13:02:26
     * @param [] type
     * @return Renderable
     */
    public function delete($param): array
    {
        #校验参数
        if (!isset($param['ids']) || empty($param['ids'])) {
            return $this->error(100001, '操作失败');
        }
        #查询数据是否存在
        $result =$this->model->where('id', 'in', $param['ids'])->where('is_del', '=', 0)->select()->toArray();

        if (!empty($result)) {
            #更新记录
            $update = $this->model->where('id', 'in', $param['ids'])->where('is_del', '=', 0)->update([
                'is_del' => time()
            ]);
            if ($update) {
                #同事删除支持货币
                Db::name('miner_pool_support_currency')->whereIn('miner_pool_id',$param['ids'])->update([
                    'is_del' => time()
                ]);
                #尝试记录操作日志 不影响主流程
                try {
                    $this->logger->logOperation($param['ids'], 'Minerpool', '删除', '删除矿池');
                } catch (\Exception $e) {
                    #记录日志或其他操作
                }
                return $this->success();
            } else {
                return $this->error(500001, '操作失败');
            }

        } else {
            #未找到记录返回失败
            return $this->error(400000, '未找到相关数据');
        }
    }

    /**
     * @describe
     * @author: Bobo
     * @date: 2025-02-13 11:03:36
     * @param [type] @required
     * @return Renderable
     */
    public function getFieldEnum($field = 'all')
    {
        $res = $this->model->getFieldEnum($field);
        return [
            'code' => 0,
            'data' => $res
        ];
    }
}